package com.hengyi.pda;

import android.support.v7.widget.LinearLayoutManager;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.common.adapter.helper.IRecyclerViewHelper;
import com.common.broadcastRecever.ScanDataBroadcastReceiver;
import com.common.mvp.BaseMvpActivity;
import com.common.mvp.BasePresenter;
import com.common.retrofit.ShuangTu.OrderBean;
import com.common.retrofit.base.ShuangTuMethods;
import com.common.retrofit.service.ShuangTuService;
import com.common.retrofit.subscriber.CommonSubscriber;
import com.common.retrofit.subscriber.SubscriberListener;
import com.common.utils.EmptyUtils;
import com.common.utils.LogUtils;
import com.common.utils.SizeUtils;
import com.common.widget.DividerDecoration.MarginDecoration;
import com.common.widget.recyclerview.refresh.recycleview.XRecyclerView;
import com.google.gson.Gson;
import com.hengyi.pda.adapter.SpareScanAdapter;
import com.hengyi.pda.bean.SubmitBean;
import com.hengyi.pda.submitjson.SheetSubmitBean;
import com.hengyi.pda.utils.BottomPickerUtils;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import rx.Observable;

public class SparePartAcy extends BaseMvpActivity {

    @BindView(R.id.tv_choose_time)
    TextView tvChooseTime;
    @BindView(R.id.tv_choose_value)
    TextView tvChooseValue;
    @BindView(R.id.recyclerview)
    XRecyclerView recyclerview;
    @BindView(R.id.tv_submit)
    TextView tvSubmit;
    @BindView(R.id.et_house_code)
    EditText etHouseCode;


    private ScanDataBroadcastReceiver scanDataBroadcastReceiver;
    private SpareScanAdapter adapter;
    private List<OrderBean.APPLYLISTSBean> bean = new ArrayList<>();
    private OrderBean orderBean;
    private List<String> applyList;
    private OptionsPickerView siteTypePicker;
    private OrderBean filter;
    private SubmitBean submitBean;
    private List<SubmitBean.APPLYLISTSBean> subList;

    @Override
    protected BasePresenter createPresenterInstance() {
        return null;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_jibeijian;
    }

    @Override
    protected void onViewCreated() {

    }

    @Override
    protected void doLogicFunc() {
        attachClickListener(tvChooseTime);
        attachClickListener(tvSubmit);
        attachClickListener(tvChooseValue);
        //二维码扫描初始化

        openScanEnable();
        scanOutputDisable();
        submitBean = new SubmitBean();
        subList = new ArrayList<>();
        scanDataBroadcastReceiver = new ScanDataBroadcastReceiver(new ScanDataBroadcastReceiver.PdaCallBack() {
            @Override
            public void setinfo(String s) {
                if (EmptyUtils.isEmpty(getTextViewStr(tvChooseTime)) || EmptyUtils.isEmpty(getTextViewStr(tvChooseValue)) || EmptyUtils.isEmpty(getEditTextStr(etHouseCode))) {
                    showToastMsg("请填入完整参数");
                    return;
                }
                if (isAccept) {
                    System.out.println("code: " + s);
                    if (hasScan(s)) {
                        showToastMsg("请不要重复扫码！");
                    } else { // 没有扫过
                        // 先判断是不是这个物料号的  再判断
                        if (isThisOrder(s, filter)) {   // 是
                            SubmitBean.APPLYLISTSBean sa = new SubmitBean.APPLYLISTSBean();
                            sa.APPLY_NUM = 1.0;
                            sa.ID = s;
                            sa.HOUSE_CODE = getEditTextStr(etHouseCode);
                            subList.add(sa);
                            submitBean.APPLYLISTS = subList;
                            adapter.setList(submitBean.APPLYLISTS);
                        } else {
                            showToastMsg("不符合规则");
                        }
                    }
//              bean.add(s);
//                    adapter.setList(bean);


                }

            }
        });
        setScanReceiver(scanDataBroadcastReceiver);
        setReclerview();

    }

    private boolean isThisOrder(String s, OrderBean filter) {
        if (EmptyUtils.isNotEmpty(filter) && EmptyUtils.isNotEmpty(filter.APPLYLISTS) && filter.APPLYLISTS.size() > 0) {
            for (int i = 0; i < filter.APPLYLISTS.size(); i++) {
                if (s.contains(filter.APPLYLISTS.get(i).SP_CODE)) {
                    return true;
                }
            }
            return false;
        }
        return false;
    }

    private boolean hasScan(String s) {
        if (EmptyUtils.isNotEmpty(submitBean) && EmptyUtils.isNotEmpty(submitBean.APPLYLISTS) && submitBean.APPLYLISTS.size() > 0) {
            for (int i = 0; i < submitBean.APPLYLISTS.size(); i++) {
                if (s.equals(submitBean.APPLYLISTS.get(i).ID)) {
                    return true;
                }
            }
            return false;
        }
        return false;
    }

    private void getOrder(String APPLYDATE) {
        showProgressingDialog();
        CommonSubscriber<OrderBean> subscriber = new CommonSubscriber<>(new SubscriberListener() {
            @Override
            public void onNext(Object o) {
                orderBean = (OrderBean) o;
                dismissProgressDialog();
                if (EmptyUtils.isNotEmpty(orderBean)) {
                    applyList = getApplyCodeList(orderBean);
                }


            }

            @Override
            public void onError(String e, int code) {
                dismissProgressDialog();
                showToastMsg(e);
            }
        });

 /*       JsonObject obj = new JsonObject();

        obj.addProperty("id", "test");
        obj.addProperty("password", "test");


        String route = new Gson().toJson(obj);
        System.out.println("aaaa" + route);
        LogUtils.e(route);*/

        SheetSubmitBean bean = new SheetSubmitBean();
//        bean.sap = "222"  ;
        bean.APPLYDATE = APPLYDATE;
        String route = new Gson().toJson(bean);
        LogUtils.e(route);
        RequestBody body = RequestBody.create(MediaType.parse("text/plan; charset=utf-8"), route);
        Observable observable = ShuangTuMethods.getRetrofit("sap/bc/zh/eam/").create(ShuangTuService.class).
                spapplylist(body);
        ShuangTuMethods.getInstance().toOtherSubscribe(observable, subscriber);
        rxManager.add(subscriber);
    }

    private List<String> getApplyCodeList(OrderBean orderBean) {
        TreeSet set = new TreeSet();
        List<String> retrunStrs = new ArrayList<>();
        if (orderBean != null) {
            if (EmptyUtils.isNotEmpty(orderBean.APPLYLISTS) && orderBean.APPLYLISTS.size() > 0) {
                for (int i = 0; i < orderBean.APPLYLISTS.size(); i++) {
                    set.add(orderBean.APPLYLISTS.get(i).APPLY_CODE);
                }
            }
            for (Iterator iter = set.iterator(); iter.hasNext(); ) {
                retrunStrs.add((String) iter.next());
            }
        }
        return retrunStrs;
    }

    private void setReclerview() {
        adapter = new SpareScanAdapter(context, submitBean.APPLYLISTS);
        IRecyclerViewHelper.init().setRecycleLineLayout(context, LinearLayoutManager.VERTICAL, recyclerview);
        recyclerview.addItemDecoration(new MarginDecoration(LinearLayoutManager.VERTICAL, (int) SizeUtils.dp2px(context, 10), true));
        recyclerview.setRefreshEnabled(false);
        recyclerview.setLoadMoreEnabled(false);
        recyclerview.setHasFixedSize(true);
        recyclerview.setAdapter(adapter);
    }

    @Override
    protected void onViewClicked(View view) {
        if (view.getId() == tvChooseTime.getId()) {
            Calendar startTime = Calendar.getInstance();
            int year = startTime.get(Calendar.YEAR);    //获取年
            int month = startTime.get(Calendar.MONTH);   //获取月份，0表示1月份
            int day = startTime.get(Calendar.DAY_OF_MONTH);    //获取当前天数
            startTime.set(year, month, day);
            Calendar endTime = Calendar.getInstance();
            endTime.set(2099, 0, 1);
            Calendar selectTime = Calendar.getInstance();
            MyDatePickerRepaymentDate myDatePickerCallBack = new MyDatePickerRepaymentDate();
            BottomPickerUtils.showDatePicker(context, endTime, startTime, selectTime, myDatePickerCallBack);
        } else if (view.getId() == tvSubmit.getId()) {
//            String strs = "";
//            HashMap<Integer, String> contents = adapter.contents;
//            Set<Integer> keys = contents.keySet();
//            Iterator<Integer> iterator = keys.iterator();
//            while (iterator.hasNext()) {
//                Integer next = iterator.next();
//                String s = contents.get(next);
//                strs = strs + "," + s;
//            }
//            showToastMsg(strs);
            System.out.println(adapter.mData.get(0).APPLY_NUM + "sbbbbbbbbbbbbbbbbbbbbb");
            System.out.println(adapter.mData.size() + "sbbbbbbbbbbbbbbbbbbbbb");
            gotoSubmit();
        } else if (view.getId() == tvChooseValue.getId()) {

            siteTypePicker = new OptionsPickerView.Builder(context, new OptionsPickerView.OnOptionsSelectListener() {

                @Override
                public void onOptionsSelect(int options1, int options2, int options3, View v) {

                    tvChooseValue.setText(applyList.get(options1));
                    getAdapterList(applyList.get(options1));

                }
            }).setSubmitText(getString(R.string.insure)).
                    setCancelText(getString(R.string.cacal)).
                    build();
            siteTypePicker.setPicker(applyList);
            if (siteTypePicker != null) {
                siteTypePicker.show();
            }
        }
    }

    private void gotoSubmit() {
        showProgressingDialog();
        CommonSubscriber<Object> subscriber = new CommonSubscriber<>(new SubscriberListener() {
            @Override
            public void onNext(Object o) {
                dismissProgressDialog();
//                submitBean = new SubmitBean() ;
                subList.clear();
                submitBean.APPLYLISTS = new ArrayList<>();
                adapter.setList(subList);


            }

            @Override
            public void onError(String e, int code) {
                dismissProgressDialog();
                showToastMsg(e);
            }
        });

 /*       JsonObject obj = new JsonObject();

        obj.addProperty("id", "test");
        obj.addProperty("password", "test");


        String route = new Gson().toJson(obj);
        System.out.println("aaaa" + route);
        LogUtils.e(route);*/


        String route = new Gson().toJson(submitBean);
        LogUtils.e(route);
        RequestBody body = RequestBody.create(MediaType.parse("text/plan; charset=utf-8"), route);
        Observable observable = ShuangTuMethods.getRetrofit("sap/bc/zh/eam/").create(ShuangTuService.class).
                spapplypost(body);
        ShuangTuMethods.getInstance().toOtherSubscribe(observable, subscriber);
        rxManager.add(subscriber);
    }

    private void getAdapterList(String applyCode) {
        filter = new OrderBean();

        List<OrderBean.APPLYLISTSBean> list = new ArrayList<>();
//        OrderBean.APPLYLISTSBean o = new OrderBean.APPLYLISTSBean() ;
        if (EmptyUtils.isNotEmpty(orderBean.APPLYLISTS) && orderBean.APPLYLISTS.size() > 0) {
            for (int i = 0; i < orderBean.APPLYLISTS.size(); i++) {
                if (orderBean.APPLYLISTS.get(i).APPLY_CODE.equals(applyCode)) {
                    list.add(orderBean.APPLYLISTS.get(i));
                    submitBean.APPLY_CODE = orderBean.APPLYLISTS.get(i).APPLY_CODE;
                    submitBean.FACTORY = orderBean.APPLYLISTS.get(i).FACTORY;
                }

            }
            filter.APPLYLISTS = list;
        }

    }

    @Override
    protected void setNavigation() {
        setNavigationBack("计备件");
    }

    private class MyDatePickerRepaymentDate implements BottomPickerUtils.DatePickerCallback {

        @Override
        public void onDateSelect(Calendar calendar) {
            int year = calendar.get(Calendar.YEAR);    //获取年
            int month = calendar.get(Calendar.MONTH) + 1;   //获取月份，0表示1月份
            int day = calendar.get(Calendar.DAY_OF_MONTH);    //获取当前天数
            int hour = calendar.get(Calendar.HOUR_OF_DAY);
            int min = calendar.get(Calendar.MINUTE);
            System.out.println("hour==" + hour);
            System.out.println("min==" + min);
            String time = year + "-" + month + "-" + day;
            tvChooseTime.setText(time);
            submitBean.POSTDATE = time;
            getOrder(time);
            System.out.println(year + "----------" + month + "月" + day + "日" + hour + "时" + min + "分钟");
//            tvTime.setText(year + "年" + month + "月" + day + "日" + hour + "时" + min + "分");
//            sendtime = calendar.getTimeInMillis() / 1000 + "";
//            has_choose_time = true;
//            end_time = year+"."+month+"."+day;
        }
    }

    @Override
    public void bindKnife() {
        ButterKnife.bind(this);

    }
}
